package com.tnt.dashboard;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.tnt.dashboard.HomeMenuGridButtonsAdapter.ViewHolder;
import com.tnt.dashboard.domain.MenuInfo;
import com.tnt.notice.NoticeAdapter;
import com.tnt.notice.NoticeInfo;

public class HomeActivity extends DashboardActivity {
	
	// 환경설정
	
	// Menu Info.
	private ArrayList<MenuInfo> mMenuList = null;
	private HomeMenuGridButtonsAdapter mMenuAdapter;
	
	// 공지사항 
	private ArrayList<NoticeInfo> mNoticeList = null;
	private TextView  mTextNotice;
	private Animation fadeIn = null;
	private Animation fadeOut = null;
    private LocalFadeInAnimationListener myFadeInAnimationListener = new LocalFadeInAnimationListener();
    private LocalFadeOutAnimationListener myFadeOutAnimationListener = new LocalFadeOutAnimationListener();
	private int iLoop=0;      // Animation Loop
	private int iRssSize=0;   // mNoticeData Array Size

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
    
        // Menu 정보를 구함.
        mMenuList    = getMenuInfo();
        mMenuAdapter = new HomeMenuGridButtonsAdapter(this,mMenuList);
        
        GridView gridview = (GridView) findViewById(R.id.buttons_grid);
        gridview.setAdapter(mMenuAdapter);
        gridview.setOnItemClickListener(mItemClickListener);
        
		mTextNotice = (TextView)findViewById(R.id.tvNotice);        
    	mTextNotice.setOnClickListener(this);	
		
		// 다른 화면에서 홈으로 전환시 공지사항을 재실행 중...
		createNoticeThread();
    }
    
	@Override
	public void onClick(View arg0) {
		Intent intent = null;
		switch (arg0.getId()){
		case R.id.tvNotice:			
			if (mNoticeList.size() > 0){

				intent = new Intent(this, com.tnt.notice.ActivityNotice.class);
				NoticeInfo mItem = mNoticeList.get(iLoop);
				
				intent.putExtra("URL"        , mItem.getLink()   );
				intent.putExtra("TITLE"      , mItem.getTitle()  );
				intent.putExtra("DESCRIPTION", mItem.getDescription()   );
				intent.putExtra("DATE"       , mItem.getPubdate());		
				
				startActivity(intent);
			}	
			break;
		
		}		
	
	}	
    
	// our handle for listener
	private OnItemClickListener mItemClickListener = new OnItemClickListener() {
	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

	    	ViewHolder holder = (ViewHolder)view.getTag();
	        if(holder == null) {
	            return;
	        }
	        toast("Clicked : " + holder.menuId + "-" +holder.tvMenuName.getText());
	        
	        // 메뉴ID에 따른 Activity호출.
			Intent intent = new Intent(HomeActivity.this, F1Activity.class);
			startActivity(intent);
	    }
	};
    
    private ProgressDialog loagindDialog; // Loading Dialog
    void createNoticeThread() {
        /* ProgressDialog */
        loagindDialog = ProgressDialog.show(this, "",
                "공지사항 가져오는 중...", true, false);
       
        Thread thread = new Thread(new Runnable() {
            public void run() {
                // 공지사항 
                String url = "http://rss.cbs.co.kr/nocutnews.xml";
                NoticeAdapter noticeAdapter = new NoticeAdapter();
                mNoticeList = noticeAdapter.getData(url);
                handler.sendEmptyMessage(0);
            }
        });
        thread.start();
    }	
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            loagindDialog.dismiss(); // 다이얼로그 삭제
            // View갱신
    		runAnimations();
        }
    };    
    
    /**
     * Starts the animation
     */
    private void runAnimations() {
    	// Setup fadein/out animations
	    fadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
	    fadeIn.setAnimationListener( myFadeInAnimationListener );
	    fadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);
	    fadeOut.setAnimationListener( myFadeOutAnimationListener );
	    
	    // And start
    	iRssSize = mNoticeList.size();    	
    	if (iRssSize > 0) launchInAnimation();    	
    }
    
    // Runnables to start the actual animation
    private Runnable mLaunchFadeInAnimation = new Runnable() {
	    public void run() {
	    	launchInAnimation();
	    }
    };        
    private Runnable mLaunchFadeOutAnimation = new Runnable() {
	    public void run() {
	    	launchOutAnimation();
	    }
    };    
    
    /**
     * Performs the actual fade-in
     */
    private void launchInAnimation() {
    	
    	NoticeInfo mItem = mNoticeList.get(iLoop);
    	String sTitle = mItem.getTitle();
       	
    	mTextNotice.setText(sTitle);
    	mTextNotice.startAnimation(fadeIn);
	    
	    iLoop++;
	    if ( iLoop == iRssSize) iLoop=0;
    }    
    
    /**
     * Performs the actual fade-out
     */
    private void launchOutAnimation() {
    	mTextNotice.startAnimation(fadeOut);
    }    
    
    /**
     * Animation listener for fade-out
     */
    private class LocalFadeInAnimationListener implements AnimationListener {
    	
	    public void onAnimationEnd(Animation animation) {
	    	mTextNotice.post(mLaunchFadeOutAnimation);
		}		
	    public void onAnimationRepeat(Animation animation){
	    }	
	    public void onAnimationStart(Animation animation) {
	    }
    };
    
    /**
     * Animation listener for fade-in
     */
    private class LocalFadeOutAnimationListener implements AnimationListener {
    	
	    public void onAnimationEnd(Animation animation) {
	    	mTextNotice.post(mLaunchFadeInAnimation);
		}		
	    public void onAnimationRepeat(Animation animation) {
	    }	
	    public void onAnimationStart(Animation animation) {
	    }
    };	    
    
    public ArrayList<MenuInfo> getMenuInfo(){
    	
    	ArrayList<MenuInfo> mMenuList = new ArrayList<MenuInfo>();
    	MenuInfo menuInfo = null;
        Resources res = getResources();
    	
    	menuInfo = new MenuInfo();
    	menuInfo.setMenuId("A");
    	menuInfo.setMenuName("입고관리");
    	menuInfo.setMenuEventCount("10");
    	menuInfo.setMenuIcon(BitmapFactory.decodeResource(res, R.drawable.app_browser));
    	mMenuList.add(menuInfo);
    	
    	menuInfo = new MenuInfo();
    	menuInfo.setMenuId("B");
    	menuInfo.setMenuName("저장관리");
    	menuInfo.setMenuEventCount("0");    	
    	menuInfo.setMenuIcon(BitmapFactory.decodeResource(res, R.drawable.app_clock));
    	mMenuList.add(menuInfo);
    	
    	menuInfo = new MenuInfo();
    	menuInfo.setMenuId("C");
    	menuInfo.setMenuName("출고관리");
    	menuInfo.setMenuEventCount("20");
    	menuInfo.setMenuIcon(BitmapFactory.decodeResource(res, R.drawable.app_display));    	
    	mMenuList.add(menuInfo);
    	
    	menuInfo = new MenuInfo();
    	menuInfo.setMenuId("D");
    	menuInfo.setMenuName("배송관리");
    	menuInfo.setMenuEventCount("9");
    	menuInfo.setMenuIcon(BitmapFactory.decodeResource(res, R.drawable.app_media));    	
    	mMenuList.add(menuInfo);

    	menuInfo = new MenuInfo();
    	menuInfo.setMenuId("E");
    	menuInfo.setMenuName("작업일보");
    	menuInfo.setMenuEventCount("0");
    	menuInfo.setMenuIcon(BitmapFactory.decodeResource(res, R.drawable.app_printer));    	
    	mMenuList.add(menuInfo);
    	
    	return mMenuList;
    }
}